package com.shuai.analysis.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shuai.analysis.domain.request.ChartAlyRequest;
import com.shuai.analysis.domain.request.ChartQueryRequest;
import com.shuai.analysis.domain.vo.ChartInfoVO;
import com.shuai.analysis.service.ChartInfoService;
import com.shuai.analysis.domain.entity.ChartInfo;
import com.shuai.analysis.mapper.ChartInfoMapper;
import com.shuai.common.constant.ChartAnalysisStatus;
import com.shuai.common.constant.ErrorCode;
import com.shuai.common.constant.RabbitMQExchangeEnum;
import com.shuai.common.constant.RabbitQueueEnum;
import com.shuai.common.exception.BusinessException;
import com.shuai.analysis.utils.ExcelHandleUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author bxs
 * @description 针对表【chart_info(可视化图表表)】的数据库操作Service实现
 * @createDate 2024-07-14 22:23:09
 */
@Service
public class ChartInfoServiceImpl extends ServiceImpl<ChartInfoMapper, ChartInfo>
        implements ChartInfoService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public boolean analysis(MultipartFile file, String userId, ChartAlyRequest chartAlyRequest) {
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        if (!(Objects.equals(suffix, "xlsx") || Objects.requireNonNull(suffix).equals("xls"))) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件格式错误");
        }

        // 将文件转换为字符串
        String excelOriginData = ExcelHandleUtils.handleExcelToStr(file);
        if (CharSequenceUtil.isBlank(excelOriginData)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件内容错误");
        }

        // 创建图表数据保存，像消息队列中发送消息等待AI订阅者处理
        ChartInfo chartInfo = ChartInfo.builder()
//                .chartType(chartAlyRequest.getChartType())
                .chartData(excelOriginData)
                .goal(chartAlyRequest.getGoal())
                .name(chartAlyRequest.getName())
                .status(ChartAnalysisStatus.SUBMITTED.getCode())
                .userId(Long.parseLong(userId))
                .build();

        // 保存图表数据（代处理）
        if (!this.save(chartInfo)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统异常，请稍后重试");
        }

        // 将消息提交到消息队列中
        rabbitTemplate.convertAndSend(RabbitMQExchangeEnum.COMMON_EXCHANGE_DIRECT_XS_AI_STATION.name,
                RabbitQueueEnum.COMMON_QUEUE_XS_AI_STATION.routingKey,
                chartInfo.getId());
        return true;
    }

    @Override
    public PageInfo<ChartInfoVO> conditionList(ChartQueryRequest chartQueryRequest, String userId) {

        LambdaQueryWrapper<ChartInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!CharSequenceUtil.isBlank(userId), ChartInfo::getUserId, userId);
        queryWrapper.like(!CharSequenceUtil.isBlank(chartQueryRequest.getName()), ChartInfo::getName, chartQueryRequest.getName());
        queryWrapper.eq(!CharSequenceUtil.isBlank(chartQueryRequest.getChartType()), ChartInfo::getChartType, chartQueryRequest.getChartType());
        queryWrapper.orderByDesc(ChartInfo::getUpdateTime);

        // 分页查询
        PageHelper.startPage(chartQueryRequest.getPage(), chartQueryRequest.getPageSize());
        List<ChartInfo> chartInfoList = this.list(queryWrapper);

        // 将分页结果转换为 PageInfo
        PageInfo<ChartInfo> pageInfo = new PageInfo<>(chartInfoList);

        // 转换为 VO 对象
        List<ChartInfoVO> chartInfoVOS = chartInfoList.stream().map(chartInfo -> {
            ChartInfoVO chartInfoVO = new ChartInfoVO();
            BeanUtils.copyProperties(chartInfo, chartInfoVO);
            return chartInfoVO;
        }).collect(Collectors.toList());

        // 将 VO 对象的分页结果设置到 PageInfo 中
        PageInfo<ChartInfoVO> resultPageInfo = new PageInfo<>();
        resultPageInfo.setTotal(pageInfo.getTotal());
        resultPageInfo.setList(chartInfoVOS);
        resultPageInfo.setPageNum(pageInfo.getPageNum());
        resultPageInfo.setPageSize(pageInfo.getPageSize());
        resultPageInfo.setPages(pageInfo.getPages());

        return resultPageInfo;
    }
}




